﻿package hapi.ui;

import flash.MovieClip;
import hapi.ui.FlashButton;
import hapi.ui.FlashSlider;
import hapi.event.Notifier;
import hapi.event.Dispatcher;
import hapi.ui.NumericValueHolder;
import hapi.ui.Slider;
import hapi.ui.Button;

typedef ScrollEvent = NumericValueChangeEvent;

class FlashScrollBar implements NumericValueHolder, implements Interactive {
	
	public var onChange(default, null):Notifier<NumericValueChangeEvent>;
	var onChangeDispatcher:Dispatcher<NumericValueChangeEvent>;
	
	public var min(getMin, setMin):Float;
	public var max(getMax, setMax):Float;
	
	var skin:FlashScrollBarSkin;
	var up:FlashButton;
	var down:FlashButton;
	var slider:FlashSlider;
	
	public function new(skin, ?min=0., ?max=1.) {
		initSkin(skin, min, max);
		initNotifiers();
		initHandlers();
	}
	
	public function change(value) {
		return slider.change(value);
	}
	
	public function increase(delta:Float):Float {
		return slider.increase(delta);
	}
	
	public function show() {
		this.skin._visible = true;
	}
	
	public function hide() {
		this.skin._visible = false;
	}
	
	public function enable() {
		slider.enable();
		up.enable();
		down.enable();
	}
	
	public function disable() {
		slider.disable();
		up.disable();
		down.disable();
	}
	
	public function isEnabled() {
		return slider.isEnabled();
	}
	
	private function initSkin(mc, min, max) {
		this.skin = mc;
		this.up = new FlashButton(skin.up);
		this.down = new FlashButton(skin.down);
		this.slider = new FlashSlider(skin.slider);
		this.slider.valueMax = max;
		this.slider.valueMin = min;
	}
	
	private function initNotifiers() {
		onChange = cast (onChangeDispatcher = new hapi.event.HapiDispatcher());
	}
	
	private function initHandlers() {
		slider.onChange.call( handleSliderChange );
		up.onPress.call( handleButtonPress );
		down.onPress.call( handleButtonPress );
	}
	
	private function handleSliderChange(event:SliderChangeEvent) {
		event.source = this;
		onChangeDispatcher.dispatchEvent(event);
	}
	
	private function handleButtonPress( event:ButtonPressEvent ) {
		var diff = Math.abs(max - min) / getSteps();
		if ( max < min ) diff = - diff;
		slider.change( slider.currentValue + (event.source == up ? -diff : diff ) );
	}
	
	private function getSteps() {
		return 10;//TODO
	}
	
	private function getMin() {
		return this.slider.valueMin;
	}
	
	private function setMin(min) {
		return slider.valueMin = min;
	}
	
	private function getMax() {
		return slider.valueMax;
	}
	
	private function setMax(max) {
		return slider.valueMax = max;
	}
}

typedef FlashScrollBarSkin = { > MovieClip,
	var up:FlashButtonSkin;
	var down:FlashButtonSkin;
	var slider:FlashSliderSkin;
}